<template>
  <div class="role-management animate-in">
    <div class="role-card">
      <el-row justify="start" align="middle" style="margin-bottom: 16px; gap: 12px;">
        <el-col style="flex: none;">
          <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 120px; margin-right: 8px;">
            <el-option label="全部" :value="''" />
            <el-option label="启用" :value="'enabled'" />
            <el-option label="禁用" :value="'disabled'" />
          </el-select>
        </el-col>
        <el-col style="flex: none;">
          <el-input v-model="filterText" placeholder="搜索角色名" clearable style="width: 200px;" />
        </el-col>
        <el-col style="flex: none;">
          <el-button class="create-role-btn" @click="openCreateDialog">新建角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="pagedTableData" row-key="Id" style="width: 100%" v-loading="loading" class="pretty-table">
        <el-table-column prop="RoleName" label="角色名" align="left" />
        <el-table-column prop="DataScope" label="数据范围" align="left" />
        <el-table-column label="权限" align="center">
          <template #default="scope">
            <div class="permission-tags-row">
              <el-tag v-for="p in (scope.row.Permissions || [])" :key="p.Id" class="pretty-tag">
                {{ p.PermissionName }}
              </el-tag>
              <span v-if="!scope.row.Permissions || scope.row.Permissions.length === 0">无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="IsActived" label="启用状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.IsActived ? 'success' : 'info'">
              {{ scope.row.IsActived ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="role-actions-row">
              <el-button size="small" @click="openAssignDialog(scope.row)">
                <el-icon><Setting /></el-icon>
                分配权限
              </el-button>
              <el-button
                size="small"
                :type="scope.row.IsActived ? 'danger' : 'success'"
                @click="toggleRoleStatus(scope.row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ scope.row.IsActived ? '禁用' : '启用' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新建角色对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建角色" width="400px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="80px">
        <el-form-item label="角色名" prop="RoleName">
          <el-input v-model="createForm.RoleName" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="数据范围" prop="DataScope">
          <el-select v-model="createForm.DataScope" placeholder="请选择数据范围">
            <el-option label="全部" value="All" />
            <el-option label="本人" value="Self" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false" :disabled="createLoading">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="createLoading">
          {{ createLoading ? '创建中...' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配权限" width="500px">
      <el-form :model="assignForm" label-width="80px">
        <el-form-item label="角色名">
          <el-input v-model="assignForm.RoleName" disabled />
        </el-form-item>
        <el-form-item label="权限">
          <div v-if="allPermissions.length === 0" style="text-align: center; color: #999; padding: 20px;">
            正在加载权限列表...
          </div>
          <div v-else>
            <div style="margin-bottom: 8px; font-size: 12px; color: #666;">
              已选择 {{ assignForm.PermissionIds.length }} 个权限
            </div>
            <div class="permission-scroll-area">
              <el-checkbox-group v-model="assignForm.PermissionIds" @change="onPermissionChange">
                <div v-for="perm in allPermissions" :key="perm.Id" class="permission-checkbox-item">
                  <el-checkbox :label="perm.Id">
                    <span class="permission-name">{{ perm.PermissionName }}</span>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssign" :loading="assignLoading">
          {{ assignLoading ? '处理中...' : '保存权限' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Setting, SwitchButton, Loading } from '@element-plus/icons-vue'
import { getRoleList, createRole, updateRole, deleteRole, assignPermissions, removePermission, getRolePermissions, toggleRoleStatus as toggleRoleStatusApi } from '@/api/role'
import { getPermissionList } from '@/api/permission'

const roles = ref([])
const loading = ref(false)
const createDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const assignLoading = ref(false)
const createLoading = ref(false)
const createForm = reactive({ RoleName: '', DataScope: 'Self' })
const createRules = { 
  RoleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  DataScope: [{ required: true, message: '请选择数据范围', trigger: 'change' }]
}
const createFormRef = ref()
const assignForm = reactive({ RoleId: '', RoleName: '', PermissionIds: [] })
const allPermissions = ref([])
const statusFilter = ref('')
const filterText = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const tableData = computed(() => Array.isArray(roles.value) ? roles.value.slice() : [])

const filteredTableData = computed(() => {
  let data = tableData.value
  if (statusFilter.value === 'enabled') {
    data = data.filter(item => item.IsActived)
  } else if (statusFilter.value === 'disabled') {
    data = data.filter(item => !item.IsActived)
  }
  if (filterText.value) {
    const keyword = filterText.value.trim().toLowerCase()
    data = data.filter(item =>
      (item.RoleName && item.RoleName.toLowerCase().includes(keyword))
    )
  }
  return data
})

// 分页后的数据
const pagedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTableData.value.slice(start, end)
})

// 分页处理函数
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 添加缓存机制
const roleCache = ref(new Map())
const permissionCache = ref(new Map())

// 优化的角色数据获取函数
async function fetchRoles() {
  loading.value = true
  
  try {
    // 1. 获取角色列表
    const roleRes = await getRoleList()
    
    if (!roleRes?.Data) {
      roles.value = []
      return
    }
    
    const roleList = roleRes.Data
    
    // 2. 并发获取所有角色的权限信息
    const rolePermissionsPromises = roleList.map(async role => {
      try {
        const permRes = await getRolePermissions(role.Id)
        return { 
          roleId: role.Id, 
          permissions: permRes?.Data || [] 
        }
      } catch {
        return { roleId: role.Id, permissions: [] }
      }
    })
    
    const rolePermissionsResults = await Promise.all(rolePermissionsPromises)
    
    // 3. 构建角色权限映射并组装数据
    const rolePermissionsMap = new Map()
    rolePermissionsResults.forEach(result => {
      rolePermissionsMap.set(result.roleId, result.permissions)
    })
    
    // 4. 组装角色数据
    roleList.forEach(role => {
      role.Permissions = rolePermissionsMap.get(role.Id) || []
    })
    
    roles.value = roleList
    
    // 5. 更新缓存
    roleList.forEach(role => roleCache.value.set(role.Id, role))
    
  } catch (error) {
    console.error('获取角色数据失败:', error)
    ElMessage.error('获取角色数据失败')
    roles.value = []
  } finally {
    loading.value = false
  }
}

// 优化的权限获取函数（使用缓存）
async function fetchPermissions() {
  // 如果缓存中有数据，直接使用
  if (allPermissions.value.length > 0) {
    return
  }
  
  try {
    const res = await getPermissionList()
    
    if (res?.Data) {
      allPermissions.value = res.Data
      // 更新缓存
      res.Data.forEach(perm => permissionCache.value.set(perm.Id, perm))
    } else {
      allPermissions.value = []
      ElMessage.warning('未获取到权限列表')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    allPermissions.value = []
    ElMessage.error('获取权限列表失败')
  }
}

function openCreateDialog() {
  createForm.RoleName = ''
  createForm.DataScope = 'Self'
  createDialogVisible.value = true
}

function handleCreate() {
  createFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    createLoading.value = true
    try {
      const res = await createRole({
        RoleName: createForm.RoleName,
        DataScope: createForm.DataScope
      })
      
      if (res && res.Code === 200) {
        ElMessage.success('角色创建成功')
        createDialogVisible.value = false
        // 重置表单
        createForm.RoleName = ''
        createForm.DataScope = 'Self'
        createFormRef.value.resetFields()
        // 刷新角色列表
        fetchRoles()
      } else {
        ElMessage.error(res.Message || '创建失败')
      }
    } catch (error) {
      console.error('创建角色失败:', error)
      if (error.response && error.response.data && error.response.data.Message) {
        ElMessage.error(error.response.data.Message)
      } else {
        ElMessage.error('创建角色失败，请重试')
      }
    } finally {
      createLoading.value = false
    }
  })
}

async function openAssignDialog(row) {
  assignForm.RoleId = row.Id
  assignForm.RoleName = row.RoleName
  assignForm.PermissionIds = (row.Permissions || []).map(p => p.Id)
  assignDialogVisible.value = true
  
  await fetchPermissions()
}

function onPermissionChange(value) {
  // 直接更新，不需要 nextTick，因为 el-checkbox-group 已经处理了双向绑定
  assignForm.PermissionIds = value
}

// 优化的权限分配函数
async function handleAssign() {
  assignLoading.value = true
  
  try {
    const currentRole = roles.value.find(r => r.Id === assignForm.RoleId)
    const currentPermissionIds = (currentRole?.Permissions || []).map(p => p.Id)
    
    // 计算需要添加和移除的权限
    const permissionsToAdd = assignForm.PermissionIds.filter(id => !currentPermissionIds.includes(id))
    const permissionsToRemove = currentPermissionIds.filter(id => !assignForm.PermissionIds.includes(id))
    
    // 并发处理权限分配和移除
    const promises = []
    
    // 添加新权限
    for (const permId of permissionsToAdd) {
      promises.push(assignPermissions(assignForm.RoleId, permId))
    }
    
    // 移除权限
    for (const permId of permissionsToRemove) {
      promises.push(removePermission(assignForm.RoleId, permId))
    }
    
    // 等待所有请求完成
    if (promises.length > 0) {
      await Promise.all(promises)
      ElMessage.success('权限分配成功')
    } else {
      ElMessage.info('权限没有变化')
    }
    
    assignDialogVisible.value = false
    
    // 清除缓存，强制重新获取数据
    roleCache.value.clear()
    await fetchRoles()
    
  } catch (error) {
    console.error('权限分配失败:', error)
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message)
    } else {
      ElMessage.error('权限分配失败，请重试')
    }
  } finally {
    assignLoading.value = false
  }
}

// 优化的角色状态切换函数
async function toggleRoleStatus(row) {
  try {
    const res = await toggleRoleStatusApi(row.Id, row.IsActived)
    
    if (res?.Code === 200) {
      ElMessage.success(res.Message || (row.IsActived ? '禁用成功' : '启用成功'))
      // 只更新当前角色的状态，避免重新获取所有数据
      row.IsActived = !row.IsActived
    } else if (res?.Message) {
      ElMessage.error(res.Message)
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('切换角色状态失败:', error)
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => {
  fetchRoles()
})
</script>

<style scoped>
.role-management {
  background: #f5f7fa;
  min-height: calc(100vh - 52px);
  padding: 0 0 60px 0;
}
.role-card {
  background: transparent;
  border-radius: 18px;
  box-shadow: none;
  padding: 8px 24px 24px 24px;
  max-width: 100%;
  margin: 0 auto;
  height: calc(100vh - 172px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.role-title {
  font-size: 24px;
  color: #222f3e;
  font-weight: 700;
  margin-bottom: 18px;
  letter-spacing: 1px;
}
.pretty-table {
  background: transparent !important;
  border-radius: 14px;
  font-size: 16px;
  width: 100%;
  flex: 1;
  overflow: hidden;
}
.pretty-table th {
  background: #f5f7fa !important;
  color: #3a4664;
  font-weight: 700;
  border-bottom: 1.5px solid #e6e8eb !important;
  letter-spacing: 0.5px;
  font-size: 15px;
  padding: 14px 12px !important;
  text-align: left !important;
}
.pretty-table td {
  background: #fff !important;
  border-bottom: 1.5px solid #f0f0f0 !important;
  color: #2d3a4a;
  font-size: 15px;
  text-align: left !important;
}

.pretty-table .el-table__row:hover > td {
  background: #f0f6ff !important;
}
.el-button {
  border-radius: 4px !important;
  font-weight: 500;
  min-width: 80px;
  font-size: 14px;
  padding: 14px 20px;
  margin-right: 0;
  margin-bottom: 0;
  transition: all 0.2s;
}
.el-button:last-child {
  margin-right: 0;
}
.el-button--danger {
  background: #f56c6c !important;
  color: #ffffff !important;
  border: none !important;
}
.el-button--danger:hover {
  background: #f78989 !important;
  color: #ffffff !important;
}
.el-button--success {
  background: #67c23a !important;
  color: #ffffff !important;
  border: none !important;
}
.el-button--success:hover {
  background: #85ce61 !important;
  color: #ffffff !important;
}
.el-button--primary {
  background: #409eff !important;
  color: #ffffff !important;
  border: none !important;
}
.el-button--primary:hover {
  background: #66b1ff !important;
  color: #ffffff !important;
}
.el-button--default {
  background: #ffffff !important;
  color: #606266 !important;
  border: 1px solid #dcdfe6 !important;
}
.el-button--default:hover {
  background: #f5f7fa !important;
  color: #409eff !important;
  border-color: #c6e2ff !important;
}
.pretty-tag {
  background: #f0f9ff !important;
  color: #0369a1 !important;
  border: 1px solid #bae6fd !important;
  border-radius: 6px !important;
  padding: 4px 10px !important;
  font-weight: 400;
  font-size: 12px;
  margin-right: 6px;
  margin-bottom: 4px;
  box-shadow: none;
  display: inline-block;
  max-width: none;
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  letter-spacing: 0.3px;
}
.permission-tags-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  white-space: normal;
  max-width: 100%;
  gap: 0 0;
  margin-top: 2px;
  margin-bottom: 2px;
}
.create-role-btn {
  background: #409eff !important;
  color: #ffffff !important;
  border: none !important;
  border-radius: 4px !important;
  font-weight: 500;
  font-size: 14px;
  padding: 8px 16px !important;
  box-shadow: none;
  transition: all 0.2s;
  margin-bottom: 0;
}
.create-role-btn:hover {
  background: #337ecc !important;
  color: #ffffff !important;
}

.role-actions-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

/* 权限选择区域样式 */
.permission-scroll-area {
  max-height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 30px 0 4px;
  font-size: 14px;
  color: #333;
}

.permission-scroll-area::-webkit-scrollbar {
  width: 6px;
  background: transparent;
}

.permission-scroll-area::-webkit-scrollbar-thumb {
  background: #bcdffb;
  border-radius: 4px;
  transition: background 0.2s ease;
}

.permission-scroll-area::-webkit-scrollbar-thumb:hover {
  background: #7ec3f7;
}

.permission-scroll-area::-webkit-scrollbar-track {
  background: transparent;
}

.permission-checkbox-item {
  margin-bottom: 4px;
  padding: 0;
  border-radius: 0;
  display: flex;
  align-items: center;
}

.permission-checkbox-item .el-checkbox {
  margin-right: 0;
  width: 100%;
}

.permission-checkbox-item .el-checkbox__label {
  font-size: 14px;
  color: #333;
  font-weight: 400;
  padding-left: 4px;
}

.permission-checkbox-item:last-child {
  margin-bottom: 0;
}

/* 权限选择区域样式 */
.assign-permission-dialog {
  width: 600px;
}

.assign-permission-content {
  width: 100%;
}

.role-info-section {
  width: 100%;
  margin-bottom: 20px;
}

.role-info-item {
  width: 100%;
  margin-bottom: 10px;
}

.label {
  width: 100%;
  font-weight: 500;
}

.value {
  width: 100%;
  margin-left: 10px;
}

.selected-count {
  width: 100%;
  margin-left: 10px;
}

.permissions-section {
  width: 100%;
}

.section-title {
  width: 100%;
  font-weight: 700;
  margin-bottom: 10px;
}

.loading-state {
  width: 100%;
  text-align: center;
  color: #999;
  padding: 20px;
}

.loading-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

.permissions-grid {
  width: 100%;
}

.permission-item {
  width: 100%;
  margin-bottom: 10px;
}

.permission-content {
  width: 100%;
}

.dialog-footer {
  width: 100%;
  text-align: right;
}
</style> 